package com.easycarebn.main.utils;

import java.io.File;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.PopupMenu.OnMenuItemClickListener;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.easycarebn.main.adapter.SpinAdapter;
import com.easycarebn.main.dialog.DataResponseDialog;
import com.easycarebn.main.fragment.FragmentCalender;
import com.easycarebn.main.fragment.FragmentLogin;
import com.easycarebn.main.model.ItemMeu;
import com.easycarebn.main.quickactionmenu.ActionItem;
import com.easycarebn.main.quickactionmenu.QuickAction;
import com.easycarebn.main.quickactionmenu.QuickAction.OnActionItemClickListener;
import com.easycarebn.request.controller.ServerController;
import com.easycarebn.request.data.AccountModel;
import com.easycarebn.request.data.Advisory;
import com.easycarebn.request.data.ContactInfoResponse;
import com.easycarebn.request.data.DataItem;
import com.easycarebn.request.data.DataItemResponse;
import com.easycarebn.request.data.DoctorDetail;
import com.easycarebn.request.data.DoctorDetail.Address;
import com.easycarebn.request.data.DoctorInfo;
import com.easycarebn.request.data.DoctorScheduleResponse;
import com.easycarebn.request.data.DoctorScheduleResponse.TimeItem;
import com.easycarebn.request.data.StatusCode;
import com.easycarebn.request.data.UserResponse;
import com.easycarebn.service.request.OnRequest;
import com.easycarebn.service.request.RequestManager;
import com.easycarebn.service.volley.toolbox.BitmapLruCache;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.timbacsi.main.DetailtActivity;
import com.timbacsi.main.GcmRegister;
import com.timbacsi.main.MainActivity;
import com.timbacsi.main.R;

public class Utils {
	public final static int REQ_EDIT_AVATAR = 1;
	public final static int REQ_ATTACH_FILE = 2;
	private final static String PREF_APP = "pref_common_app";
	public final static String KEY_OPTION = "KEYOPTION";

	public final static String KEY_TYPE = "KEY_TYPE";
	public final static String phone = "0473023666";

	public final static String KEY_URL = "KEY_URL";

	public final static String KEY_USER_LOGIN = "KEY_USER_LOGIN";
	public final static String KEY_CONTACT = "KEY_CONTACT";
	public final static String TITLE = "TITLE";
	public final static String KEY_DOCTOR_ID = "KEY_DOCTOR_ID";
	public final static String KEY_ADDRESS_ID = "KEY_ADDRESS_ID";
	public final static String KEY_ADDRESS = "KEY_ADDRESS";
	public final static String KEY_ACCOUNT_MODEL = "KEY_ACCOUNT_MODEL";
	
	public final static String KEY_TITLE = "KEY_TITLE";
	public final static String KEY_PHONE = "KEY_PHONE";

	public final static String KEY_APPOINT_ID = "KEY_APPOINT_ID";
	public final static String KEY_LOCATION = "KEY_LOCATION";
	public final static String KEY_ADRESS = "KEY_ADRESS";
	public final static String KEY_ID = "KEY_ID";

	public final static String KEY_SERVICE_TYPE = "KEY_SERVICE_TYPE";

	public final static String TAG_HOME = "TAG_HOME";
	public final static String TAG_CHILD = "TAG_CHILD";
	public final static String DATE_BOOK = "DATE_BOOK";
	public final static String HOUR_BOOK = "HOUR_BOOK";
	public final static String ADDRESS_NAME = "ADDRESS_NAME";
	public final static String DATE_SHOW = "DATE_SHOW";

	public final static int TASK_HOME = 4;
	public final static int TASK_CHILD = 3;
	public final static int SELECT_TIME_BOOKING = 121;
	public final static int LIST_MESSAGE = 0;
	public final static int LOGIN = 111;
	public final static int BOOK = 29;
	public final static int ONBACK = 40;

	public final static int STEP1_BOOK = 43;
	public final static int FORGET_PASS = 39;
	public final static int MESSAGES = 445;

	public final static int CREATE_ACC = 50;

	public final static int LOGIN_CMT = 1226;
	public final static int LOGIN_BOOKING = 1227;

	public final static int ERROR = 404;
	public final static int IMG_WIDHT = 1024;
	public final static int IMG_HEIGHT = 1024;

	public final static int REMOVE_SMS = 13;

	public final static int BOOKING = 33;
	public final static int BOOK_STEP2 = 35;
	public final static int MAP = 31;
	public final static int MAP_DOCTER = 32;
	public final static int NOTIFICATION_DETAILT = 424;
	public final static int NOT_ACTIVE = 24;

	public final static int DOCTOR_SERVICE_DETAILT = 40;
	public final static int DOCTOR_SERVICE_DETAILT_PK = 41;

	public final static int RELOAD_TIME = 121;
	public final static int RELOAD_COMMENT = 122;

	public final static int APPOINTMENT_DETAIL = 42;

	public final static int SHOW_VIEW_SEARCH = 0;

	public final static int SHOW_HOME = 1;

	public final static int MAP_ALL_SEARCH_RESULT = 36;
	public final static int MAP_CONTACT = 34;
	public final static int MAP_CONTACT_DETAILT = 37;
	public final static int numberOfRecord = 3;

	// public static int LOGIN_STATUS = 0;

	public static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,3})$";
	public static final String NUMBER_PATTERN = "(.*)(\\d+)(.*)";

	public static void intentToDetailt(Activity activity, int key) {
		Intent intent = new Intent(activity, DetailtActivity.class);
		intent.putExtra(Utils.KEY_OPTION, key);
		activity.startActivityForResult(intent, key);
	}

	public static void onResumeRequest(Activity activity, View viewbig,
			final IResult callIResult) {
		final FrameLayout frameLayout = (FrameLayout) viewbig
				.findViewById(R.id.lineBig);
		final View view = activity.getLayoutInflater().inflate(
				R.layout.message_errors_wifi, null);
		TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
		tv_message.setText(Html.fromHtml(activity.getResources().getString(
				R.string.khong_co_ket_noi)));
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				frameLayout.removeView(view);
				callIResult.onDisplay(Activity.RESULT_OK, "");
			}
		});

		frameLayout.addView(view, 0);

	}

	public static void setAddress(TextView tv_address,
			ArrayList<Address> list_address) {
		String mAddressTmp = "";
		if(list_address.size()==1){
            mAddressTmp += list_address.get(0).getAddress();
            tv_address.setText(Html.fromHtml(mAddressTmp));
            return;
		}
		for (int i = 0; i < list_address.size(); i++) {
			if (list_address.get(i).getIs_default() == 1
					&& list_address.size() > 1) {
				mAddressTmp += "- <b>" + list_address.get(i).getAddress()
						+ "</b><br>";
			} else {
				if (i == list_address.size() - 1) {
					mAddressTmp += "- " + list_address.get(i).getAddress();
				} else {
					mAddressTmp += "- " + list_address.get(i).getAddress()
							+ "<br>";
				}
			}

		}
		Log.d("mAddressTmp", mAddressTmp);
		tv_address.setText(Html.fromHtml(mAddressTmp));
	}

	public static void onShowMessageNull(Activity activity, View viewbig,
			String messge) {
		final FrameLayout frameLayout = (FrameLayout) viewbig
				.findViewById(R.id.lineBig);
		final View view = activity.getLayoutInflater().inflate(
				R.layout.message_title, null);
		TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
		tv_message.setText(messge);

		frameLayout.addView(view, 0);
	}

	public static void onShowRemoveViewNull(Activity activity, View viewbig) {
		final FrameLayout frameLayout = (FrameLayout) viewbig
				.findViewById(R.id.lineBig);
		final View view = activity.getLayoutInflater().inflate(
				R.layout.message_title, null);
		TextView tv_message = (TextView) view.findViewById(R.id.tv_message);
		frameLayout.removeView(view);
	}

	public static boolean isOnline(Activity activity) {
		if (activity != null) {
			ConnectivityManager connectivity = (ConnectivityManager) activity
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			if (connectivity != null) {
				NetworkInfo[] info = connectivity.getAllNetworkInfo();
				if (info != null)
					for (int i = 0; i < info.length; i++)
						if (info[i].getState() == NetworkInfo.State.CONNECTED) {
							return true;
						}
			}
		}
		return false;

	}

	public static void gotoMapContact(Activity activity, String address,
			String location) {
		Bundle data = new Bundle();
		data.putString(Utils.KEY_ADRESS, address);
		data.putString(Utils.KEY_LOCATION, location);
		Utils.intentToDetailt(activity, Utils.MAP_CONTACT, data);

	}

	public static int convertDpToPixel(int dps, Context context) {
		Resources resources = context.getResources();
		DisplayMetrics metrics = resources.getDisplayMetrics();

		final float scale = metrics.density;
		int pixels = (int) (dps * scale + 0.5f);
		return pixels;
	}

	public static void setTextEmpty(TextView textView, Activity activity) {
		textView.setText(Html.fromHtml(Utils.setTextcolorHtml(activity
				.getResources().getString(R.string.chua_cap_nhat), "#c4c4c4")));
	}

	public static void setTextEmpty(TextView textView, Activity activity,
			String label) {
		textView.setText(Html.fromHtml(Utils.setTextcolorHtml(label + " "
				+ activity.getResources().getString(R.string.chua_cap_nhat),
				"#c4c4c4")));
	}

	public static void intentToDetailt(Activity activity, int key, Bundle data) {
		Intent intent = new Intent(activity, DetailtActivity.class);
		if (data == null) {
			intent.putExtra(Utils.KEY_OPTION, key);
		} else {
			data.putInt(Utils.KEY_OPTION, key);
			intent.putExtras(data);
		}
		activity.startActivityForResult(intent, key);
	}

	public static void callPhone(String phone, Activity activity) {
		String uri = "tel:" + phone;
		Intent intent = new Intent(Intent.ACTION_CALL);
		intent.setData(Uri.parse(uri));
		activity.startActivity(intent);
	}

	public static void getDialogTimeBook(final Activity activity,
			final IResult callIResult, final int doctorId, List<TimeItem> list,
			DoctorScheduleResponse data) {

		final Dialog dialog = new Dialog(activity);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialogtimebox);

		dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		dialog.getWindow().setBackgroundDrawableResource(android.R.color.white);
		dialog.setCanceledOnTouchOutside(true);

		TextView btnDatkhamItem = (TextView) dialog
				.findViewById(R.id.btnDatkhamItem);
		View mView = (View) dialog.findViewById(R.id.lineBookKham);
		new FragmentCalender(activity, callIResult, doctorId, list, data,
				mView, new IResult() {

					@Override
					public void onDisplay(int arg1, String arg2) {
						if (arg1 == Activity.RESULT_CANCELED) {
							dialog.dismiss();
						}
					}
				}).init();
		btnDatkhamItem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		dialog.show();

	}

	public static void gotoBooking(Activity activity, String data,
			int mServiceType) {
		// Toast.makeText(activity, "Time selected: " + data,
		// Toast.LENGTH_LONG).show();
		Log.d("data", data);
		String dataAr[] = data.split("#");
		Bundle bundle = new Bundle();
		bundle.putString(Utils.DATE_BOOK, dataAr[0]);
		bundle.putString(Utils.TITLE,
				activity.getResources().getString(R.string.lblDatkham));
		bundle.putString(Utils.HOUR_BOOK, dataAr[1]);
		bundle.putInt(Utils.KEY_SERVICE_TYPE, mServiceType);
		bundle.putInt(Utils.KEY_DOCTOR_ID, Integer.parseInt(dataAr[2]));
		bundle.putInt(Utils.KEY_ADDRESS_ID, Integer.parseInt(dataAr[3]));
		bundle.putString(Utils.ADDRESS_NAME, dataAr[4]);
		bundle.putString(Utils.DATE_SHOW, dataAr[5]);

		intentToDetailt(activity, Utils.BOOKING, bundle);
	}

	public static void getPopupMenu(final List<DataItem> list,
			Activity activity, View view, final IResult callback) {
		Log.d("getPopupMenu", "getPopupMenu");

		PopupMenu menu = new PopupMenu(activity, view);
		for (int i = 0; i < list.size(); i++) {
			menu.getMenu().add(0, i, 0, list.get(i).getName());
		}
		menu.show();
		menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

			@Override
			public boolean onMenuItemClick(MenuItem itemMn) {
				callback.onDisplay(itemMn.getItemId(), "");
				return false;
			}
		});

	}

	public static void addMenuTop(final List<DataItem> list, Activity activity,
			View view, final IResult callback) {
		final QuickAction quickAction = new QuickAction(activity,
				QuickAction.VERTICAL);

		for (int i = 0; i < list.size(); i++) {
			quickAction.addActionItem(new ActionItem(list.get(i).getId(), list
					.get(i).getName(), null), true);
		}

		quickAction.show(view);
		quickAction
				.setOnActionItemClickListener(new OnActionItemClickListener() {

					@Override
					public void onItemClick(QuickAction source, int pos,
							int actionId) {
						callback.onDisplay(pos, "" + actionId);
					}
				});
	}

	public static void showDropdow(final int type, final Activity activity,
			final List<ItemRadioSpin> listData, final IDialogResult callBack,
			String title, final int idChecked) {
		final Dialog dialog = new Dialog(activity);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.abs__menu_dropdown_panel_holo_light);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(R.layout.dialogprice);
		dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT);

		TextView lblTitle = (TextView) dialog.findViewById(R.id.lblTitle);
		if (!TextUtils.isEmpty(title)) {
			lblTitle.setText(title.toUpperCase());
		} else {
			lblTitle.setVisibility(View.GONE);
		}
		// dialog.getWindow().setLayout(width - 0, LayoutParams.MATCH_PARENT);

		ListView listView = (ListView) dialog.findViewById(R.id.listsale);

		final SpinAdapter adapter = new SpinAdapter(activity,
				R.layout.item_publicsher, listData, idChecked);
		listView.setAdapter(adapter);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				listData.get(position).setChecked(true);
				for (int i = 0; i < listData.size(); i++) {
					if (i != position) {
						listData.get(i).setChecked(false);
					}
				}
				adapter.notifyDataSetChanged();
				callBack.onResultDropdow(listData.get(position), type);
				dialog.dismiss();
			}
		});

		dialog.show();
	}

	public static boolean validate(final String value, String patt) {
		Pattern pattern = Pattern.compile(patt);
		Matcher matcher = pattern.matcher(value);
		return matcher.matches();
	}

	public static void setTitlePage(View view, String title) {
		TextView txtTitle = (TextView) view.findViewById(R.id.lblTitle);
		txtTitle.setText(title);

	}

	public static void disableEnableControls(boolean enable, View vgtmp) {
		ViewGroup vg = (ViewGroup) vgtmp;
		try {
			for (int i = 0; i < vg.getChildCount(); i++) {
				View child = vg.getChildAt(i);
				child.setEnabled(enable);
				if (child instanceof ViewGroup) {
					disableEnableControls(enable, (ViewGroup) child);
				}
			}
		} catch (Exception e) {

		}
	}

	public static void hideKeyboard(Activity activity) {
		try {
			InputMethodManager imm = (InputMethodManager) activity
					.getSystemService(Context.INPUT_METHOD_SERVICE);
			imm.hideSoftInputFromWindow(activity.getCurrentFocus()
					.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static ArrayList<ItemMeu> getMenu(Activity activity, int menu) {

		ArrayList<ItemMeu> menuItems = null;
		try {
			menuItems = new ArrayList<ItemMeu>();
			XmlResourceParser xpp = activity.getResources().getXml(menu);

			xpp.next();
			int eventType = xpp.getEventType();
			while (eventType != XmlPullParser.END_DOCUMENT) {

				if (eventType == XmlPullParser.START_TAG) {
					String elemName = xpp.getName();
					if (elemName.equals("item")) {
						String textId = xpp.getAttributeValue(
								"http://schemas.android.com/apk/res/android",
								"title");
						String iconId = xpp.getAttributeValue(
								"http://schemas.android.com/apk/res/android",
								"icon");
						String resId = xpp.getAttributeValue(
								"http://schemas.android.com/apk/res/android",
								"id");
						ItemMeu item = new ItemMeu();
						item.setTitle(textId);
						Log.d("textId", textId);
						item.setRegId(Integer.valueOf(resId.replace("@", "")));
						item.setIcon(Integer.valueOf(iconId.replace("@", "")));
						menuItems.add(item);

					}
				}
				eventType = xpp.next();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return menuItems;

	}

	public static void finishActivity(Activity activity) {
		activity.finish();
		activity.overridePendingTransition(R.anim.anim_slide_in_right,
				R.anim.anim_slide_out_right);
	}

	public static void updateData(Context context, String key, Object obj) {
		Gson gson = new Gson();
		String data = gson.toJson(obj);
		SharedPreferences pref = context.getSharedPreferences(PREF_APP,
				Context.MODE_PRIVATE);
		Editor edit = pref.edit();
		edit.putString(key, data);
		edit.commit();
	}

	public static AccountModel  getAccountModel(Context context, String key) {
		SharedPreferences pref = context.getSharedPreferences(PREF_APP,
				Context.MODE_PRIVATE);
		String data = pref.getString(key, "");
		if (TextUtils.isEmpty(data)) {
			return null;
		}
		Gson gson = new Gson();
		return gson.fromJson(data, AccountModel.class);
	}
	
	public static ArrayList<DataItem> getRemainData(Context context, String key) {
		ArrayList<DataItem> items = new ArrayList<DataItem>();
		SharedPreferences pref = context.getSharedPreferences(PREF_APP,
				Context.MODE_PRIVATE);
		String data = pref.getString(key, "");
		if (TextUtils.isEmpty(data)) {
			return items;
		}
		Type type = new TypeToken<ArrayList<DataItem>>() {
		}.getType();
		Gson gson = new Gson();
		return gson.fromJson(data, type);
	}

	/**
	 * Get logged user
	 * 
	 * @param context
	 * @return <li>UserResponse: User was logged</li> <li>Null: User wasn't
	 *         logged</li>
	 */
	public static UserResponse getUserLogin(Context context) {
		SharedPreferences pref = context.getSharedPreferences(PREF_APP,
				Context.MODE_PRIVATE);
		String data = pref.getString(KEY_USER_LOGIN, "");
		if (TextUtils.isEmpty(data)) {
			return null;
		}
		Gson gson = new Gson();
		return gson.fromJson(data, UserResponse.class);
	}

	public static ContactInfoResponse getContactInfo(Context context) {
		ContactInfoResponse mContactInfoResponse = null;
		try {
			SharedPreferences pref = context.getSharedPreferences(PREF_APP,
					Context.MODE_PRIVATE);
			String data = pref.getString(KEY_CONTACT, "");
			if (TextUtils.isEmpty(data)) {
				return null;
			}
			Gson gson = new Gson();
			mContactInfoResponse = gson.fromJson(data,
					ContactInfoResponse.class);
		} catch (Exception e) {
		}
		return mContactInfoResponse;
	}

	public static void removeUserLogin(Context context) {
		SharedPreferences pref = context.getSharedPreferences(PREF_APP,
				Context.MODE_PRIVATE);
		Editor edit = pref.edit();
		edit.remove(KEY_USER_LOGIN);
		edit.commit();
	}

	public static void updateUserLogin(Context context, UserResponse user) {
		Utils.updateData(context, Utils.KEY_USER_LOGIN, user);
	}

	public static void requestLogin(final Context context,
			final IResult callIResult, final String email, final String pwd,
			final boolean isShowMsg) {
		if (isShowMsg) {
			FragmentLogin.mLoadding.setVisibility(View.VISIBLE);
		}

		ServerController.getInstance(context).requestUserLogin(email, pwd,
				new OnRequest<UserResponse>() {

					@Override
					public void onSuccess(UserResponse data) {
						String message = "";
						// Save user login
						if (data.getCode() == StatusCode.OK) {
							Utils.updateData(context, Utils.KEY_ACCOUNT_MODEL, new AccountModel(email, pwd));
							message = context.getResources().getString(
									R.string.dang_nhap_thanh_cong);
							updateUserLogin(context, data);
							callIResult.onDisplay(
									Utils.SHOW_HOME,
									context.getResources().getString(
											R.string.lblDangnhap));
							new GcmRegister(context).newInstance();
						} else if (data.getCode() == StatusCode.NOT_ACTIVE) {
							message = context.getResources().getString(
									R.string.chua_kich_hoat);
							if (Utils.validate(email, Utils.EMAIL_PATTERN)) {
								callIResult.onDisplay(
										Utils.CREATE_ACC,
										context.getResources().getString(
												R.string.kich_hoat_tai_khoan)
												+ "-" + " ");
							} else {
								callIResult.onDisplay(
										Utils.CREATE_ACC,
										context.getResources().getString(
												R.string.kich_hoat_tai_khoan)
												+ "-" + email);
							}

						} else {
							message = context.getResources().getString(
									R.string.tai_khoan_khong_ton_tai);
							
						}

						if (isShowMsg) {
							showMessage(context, message);
							FragmentLogin.mLoadding.setVisibility(View.GONE);
						}

					}

					@Override
					public void onError(int errorCode, String message) {
						if (isShowMsg) {
							FragmentLogin.mLoadding.setVisibility(View.GONE);
						}
						if (!message.isEmpty()&&!message.equals(" "))
							showMessage(context, message);
					}
				});
	}

	public static void sendMessagesToDocter(final Activity activity,
			final String token, final DoctorDetail docter,
			final int reply_for_notification_id) {
		final DataResponseDialog dialog = new DataResponseDialog(activity) {

			@Override
			public void onResult(int requestCode, Intent intent) {
				TextView ed_dinhkem = (TextView) this
						.findViewById(R.id.ed_dinhkem);
				if (intent == null) {
					return;
				}
				Uri uri = intent.getData();
				if (uri == null) {
					return;
				}
				String file = Utils.getRealPathFromURI(activity, uri);
				String data[];
				if (!TextUtils.isEmpty(file)) {
					data = file.split("/");
					if (data != null && data.length > 0) {
						ed_dinhkem.setText(data[data.length - 1]);
					}
				}
				Log.d("UTILS", "URI: " + uri + "\n" + file);
				ed_dinhkem.setTag(file);
			}
		};
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawableResource(android.R.color.white);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(R.layout.dialog_sendmessage);

		dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);

		dialog.show();
		TextView lblMess = (TextView) dialog.findViewById(R.id.lblDesc);
		lblMess.append(Html.fromHtml("<font color='#00a3e0' <b>"
				+ docter.getName() + "</b></font>"));

		final EditText edTitle = (EditText) dialog.findViewById(R.id.edTitle);
		final ProgressBar mLoadding = (ProgressBar) dialog
				.findViewById(R.id.loadding);
		final LinearLayout lineBookKham = (LinearLayout) dialog
				.findViewById(R.id.lineBookKham);

		final EditText edInfo = (EditText) dialog.findViewById(R.id.edInfo);
		final TextView ed_dinhkem = (TextView) dialog
				.findViewById(R.id.ed_dinhkem);
		ed_dinhkem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (activity instanceof DetailtActivity) {
					((DetailtActivity) activity).setDataResponse(dialog);
					pickFile(activity, REQ_ATTACH_FILE);
				}
				if (activity instanceof MainActivity) {
					((MainActivity) activity).setDataResponse(dialog);
					pickFile(activity, REQ_ATTACH_FILE);
				}
			}
		});

		Button btnDatlichtruoc = (Button) dialog
				.findViewById(R.id.btnDatlichtruoc);

		btnDatlichtruoc.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				String edTieude = edTitle.getText().toString().trim();

				if (edTieude.length() == 0) {
					Utils.showMessage(activity, activity.getResources()
							.getString(R.string.nhap_tieu_de));
					edTitle.setFocusable(true);
					return;
				}
				String mContent = edInfo.getText().toString().trim();
				if (mContent.length() == 0) {
					Utils.showMessage(activity, activity.getResources()
							.getString(R.string.nhap_them_thong_tin));
					edInfo.setFocusable(true);
					return;
				}
				String fileName = "";
				if (ed_dinhkem != null && ed_dinhkem.getTag() != null) {
					fileName = ed_dinhkem.getTag().toString();
				}
				File file = null;
				if (!TextUtils.isEmpty(fileName)) {
					file = new File(fileName);
				}
				Utils.disableEnableControls(false, lineBookKham);
				mLoadding.setVisibility(View.VISIBLE);

				ServerController.getInstance(activity)
						.requestNotificationSendMessage(token,
								docter.getDoctorId(), edTieude, mContent, file,
								reply_for_notification_id,
								new OnRequest<DataItemResponse>() {

									@Override
									public void onSuccess(DataItemResponse data) {
										Utils.disableEnableControls(true,
												lineBookKham);
										mLoadding.setVisibility(View.GONE);

										dialog.dismiss();
										Utils.showMessage(
												activity,
												activity.getResources()
														.getString(
																R.string.gui_thanh_cong));
									}

									@Override
									public void onError(int errorCode,
											String message) {
										Utils.disableEnableControls(true,
												lineBookKham);
										mLoadding.setVisibility(View.GONE);

										dialog.dismiss();
										Utils.showMessage(activity, message);
									}
								});
			}
		});
		TextView btnDatkhamItem = (TextView) dialog
				.findViewById(R.id.btnDatkhamItem);

		btnDatkhamItem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

	}

	public static void showDatlichtruoc(final Context activity,
			final DoctorInfo docter) {
		final Dialog dialog = new Dialog(activity);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawableResource(android.R.color.white);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(R.layout.dialog_datlichtruoc);

		dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);

		dialog.show();
		TextView lblMess = (TextView) dialog.findViewById(R.id.lblDesc);
		lblMess.append(Html.fromHtml("<font color='#00a3e0' <b>"
				+ docter.getName() + "</b></font>"));
		final ProgressBar mLoadding = (ProgressBar) dialog
				.findViewById(R.id.loadding);
		final LinearLayout lineBookKham = (LinearLayout) dialog
				.findViewById(R.id.lineBookKham);

		final EditText edHoten = (EditText) dialog.findViewById(R.id.edHoten);
		final EditText edSodt = (EditText) dialog.findViewById(R.id.edSdt);
		final EditText edNoidung = (EditText) dialog.findViewById(R.id.edInfo);

		Button btnDatlichtruoc = (Button) dialog
				.findViewById(R.id.btnDatlichtruoc);

		btnDatlichtruoc.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				String mHoten = edHoten.getText().toString().trim();

				if (mHoten.length() == 0) {
					Utils.showMessage(activity, activity.getResources()
							.getString(R.string.nhap_ho_ten));
					edHoten.setFocusable(true);
					return;
				}
				String mSdt = edSodt.getText().toString().trim();
				if (mSdt.length() == 0) {
					Utils.showMessage(activity, activity.getResources()
							.getString(R.string.nhap_so_dien_thoai));
					edSodt.setFocusable(true);
					return;
				}
				if (mSdt.length() < 10 || mSdt.length() > 11) {
					Utils.showMessage(activity, activity.getResources()
							.getString(R.string.so_dien_thoai_ko_hop_le));
					edSodt.setFocusable(true);
					return;
				}

				String mNoidung = edNoidung.getText().toString().trim();
				if (mNoidung.length() == 0) {
					Utils.showMessage(activity, activity.getResources()
							.getString(R.string.nhap_noidung));
					edNoidung.setFocusable(true);
					return;
				}
				Utils.disableEnableControls(false, lineBookKham);
				mLoadding.setVisibility(View.VISIBLE);

				ServerController.getInstance(activity).requestSendAdvisory(
						docter.getId(), mHoten, mSdt, mNoidung, 2,
						new OnRequest<Advisory>() {

							@Override
							public void onSuccess(Advisory data) {
								Utils.disableEnableControls(true, lineBookKham);
								mLoadding.setVisibility(View.GONE);

								if (data == null)

									return;
								if (data.getCode() == StatusCode.OK) {
									dialog.dismiss();
									Utils.showMessage(
											activity,
											activity.getResources().getString(
													R.string.yeu_cau_dat_kham));
								} else {
									Utils.showMessage(activity,
											data.getMessages());

								}
							}

							@Override
							public void onError(int errorCode, String message) {
								Utils.disableEnableControls(true, lineBookKham);
								mLoadding.setVisibility(View.GONE);

							}
						});

			}
		});
		TextView btnDatkhamItem = (TextView) dialog
				.findViewById(R.id.btnDatkhamItem);

		btnDatkhamItem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

	}

	public static void showDatlichtruoc(final Context activity,
			final DoctorDetail docter) {
		final Dialog dialog = new Dialog(activity);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawableResource(android.R.color.white);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(R.layout.dialog_datlichtruoc);

		dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);

		dialog.show();
		TextView lblMess = (TextView) dialog.findViewById(R.id.lblDesc);
		lblMess.append(Html.fromHtml("<font color='#00a3e0' <b>"
				+ docter.getName() + "</b></font>"));

		final EditText edHoten = (EditText) dialog.findViewById(R.id.edHoten);
		final EditText edSodt = (EditText) dialog.findViewById(R.id.edSdt);
		final EditText edNoidung = (EditText) dialog.findViewById(R.id.edInfo);

		Button btnDatlichtruoc = (Button) dialog
				.findViewById(R.id.btnDatlichtruoc);

		btnDatlichtruoc.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				String mHoten = edHoten.getText().toString().trim();

				if (mHoten.length() == 0) {
					Utils.showMessage(activity, activity.getResources()
							.getString(R.string.nhap_ho_ten));
					edHoten.setFocusable(true);
					return;
				}
				String mSdt = edSodt.getText().toString().trim();
				if (mSdt.length() == 0) {
					Utils.showMessage(activity, activity.getResources()
							.getString(R.string.nhap_so_dien_thoai));
					edSodt.setFocusable(true);
					return;
				}

				String mNoidung = edNoidung.getText().toString().trim();
				if (mNoidung.length() == 0) {
					Utils.showMessage(activity, activity.getResources()
							.getString(R.string.nhap_noidung));
					edNoidung.setFocusable(true);
					return;
				}

				ServerController.getInstance(activity).requestSendAdvisory(
						docter.getDoctorId(), mHoten, mSdt, mNoidung, 2,
						new OnRequest<Advisory>() {

							@Override
							public void onSuccess(Advisory data) {
								if (data == null)
									return;
								if (data.getCode() == StatusCode.OK) {
									dialog.dismiss();
									Utils.showMessage(
											activity,
											activity.getResources().getString(
													R.string.yeu_cau_dat_kham));
								} else {
									Utils.showMessage(activity,
											data.getMessages());

								}
							}

							@Override
							public void onError(int errorCode, String message) {
								// TODO Auto-generated method stub

							}
						});

			}
		});
		TextView btnDatkhamItem = (TextView) dialog
				.findViewById(R.id.btnDatkhamItem);

		btnDatkhamItem.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

	}

	public static String setTextcolorHtml(String content, String color) {
		return "<font color='" + color + "'>" + content + "</font>";

	}

	public static void showMessage(Activity activity, String msg, View view) {
		int duration = Toast.LENGTH_SHORT;
		// Toast toast = Toast.makeText(activity, msg, duration);
		// toast.setGravity(Gravity.TOP | Gravity.RIGHT, 60, 80);
		// toast.show();

		View layout = activity.getLayoutInflater().inflate(
				R.layout.layout_toast, null);

		TextView lblContent = (TextView) layout
				.findViewById(R.id.toast_content);

		lblContent.setText(msg);
		Toast toast = new Toast(activity.getApplicationContext());
		toast.setGravity(Gravity.TOP | Gravity.RIGHT, 60, 220);
		toast.setDuration(Toast.LENGTH_SHORT);
		toast.setView(layout);

		toast.show();
	}

	public static void showMessage(Context activity, String msg) {
		int duration = Toast.LENGTH_SHORT;
		Toast toast = Toast.makeText(activity, msg, duration);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();

		/*
		 * final Dialog dialog = new Dialog(activity);
		 * dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		 * dialog.getWindow
		 * ().setBackgroundDrawableResource(android.R.color.transparent);
		 * dialog.setCanceledOnTouchOutside(true);
		 * dialog.setContentView(R.layout.dialognote);
		 * 
		 * DisplayMetrics displaymetrics = new DisplayMetrics(); ((Activity)
		 * activity
		 * ).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		 * int width = displaymetrics.widthPixels;
		 * dialog.getWindow().setLayout(5 * width / 6,
		 * LayoutParams.WRAP_CONTENT);
		 * 
		 * dialog.show(); TextView lblMess = (TextView)
		 * dialog.findViewById(R.id.lblMessage);
		 * lblMess.setText(Html.fromHtml(msg));
		 * 
		 * Button btnAccept = (Button) dialog.findViewById(R.id.btnAccept);
		 * 
		 * btnAccept.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) {
		 * 
		 * dialog.dismiss();
		 * 
		 * } });
		 */
	}

	public static void showDialogConfirm(final Context activity, String msg,
			final IResult callBack) {
		final Dialog dialog = new Dialog(activity);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.background_card);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setContentView(R.layout.dialogconfirm);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		((Activity) activity).getWindowManager().getDefaultDisplay()
				.getMetrics(displaymetrics);
		int width = displaymetrics.widthPixels;
		dialog.getWindow().setLayout(5 * width / 6, LayoutParams.WRAP_CONTENT);

		dialog.show();
		TextView lblMess = (TextView) dialog.findViewById(R.id.lblMessage);
		lblMess.setText(Html.fromHtml(msg));

		Button btnAccept = (Button) dialog.findViewById(R.id.btnAccept);

		btnAccept.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				callBack.onDisplay(Activity.RESULT_OK, "");
				dialog.dismiss();

			}
		});

		Button btnNo = (Button) dialog.findViewById(R.id.btnNo);

		btnNo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				callBack.onDisplay(Activity.RESULT_CANCELED, "");
				dialog.dismiss();

			}
		});
	}

	public static void showDialogUpdate(final Activity activity, String msg,
			final IResult callBack) {
		final Dialog dialog = new Dialog(activity);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.getWindow().setBackgroundDrawableResource(
				R.drawable.background_card);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setCancelable(false);
		dialog.setContentView(R.layout.dialogconfirm);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		((Activity) activity).getWindowManager().getDefaultDisplay()
				.getMetrics(displaymetrics);
		int width = displaymetrics.widthPixels;
		dialog.getWindow().setLayout(5 * width / 6, LayoutParams.WRAP_CONTENT);

		dialog.show();
		TextView lblMess = (TextView) dialog.findViewById(R.id.lblMessage);
		lblMess.setText(Html.fromHtml(msg));

		Button btnAccept = (Button) dialog.findViewById(R.id.btnAccept);
		btnAccept.setText("Cập nhật");
		btnAccept.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				callBack.onDisplay(Activity.RESULT_OK, "");
				activity.finish();
				System.exit(0);

			}
		});

		Button btnNo = (Button) dialog.findViewById(R.id.btnNo);
		btnNo.setVisibility(View.GONE);
		btnNo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				callBack.onDisplay(Activity.RESULT_CANCELED, "");
				dialog.dismiss();

			}
		});
	}

	public static void showMessage(Context context, int strId) {
		showMessage(context, context.getString(strId));
	}

	public static ImageLoader getImageLoader(Context context) {
		int max_cache_size = 1000000;
		return new ImageLoader(RequestManager.newInstance(context)
				.getRequestQueue(), new BitmapLruCache(max_cache_size));
	}

	public static Date convertDate(String date, String pattern) {
		Date d = new Date();
		if (TextUtils.isEmpty(date)) {
			return d;
		}
		SimpleDateFormat fm = new SimpleDateFormat(pattern, Locale.US);
		try {
			d = fm.parse(date);
			return d;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return d;
		}
	}

	public static void setOnTouchHideKeyboard(final Activity activity, View view) {

		// Set up touch listener for non-text box views to hide keyboard.
		if (!(view instanceof EditText)) {

			view.setOnTouchListener(new OnTouchListener() {

				public boolean onTouch(View v, MotionEvent event) {
					hideKeyboard(activity);
					return false;
				}

			});
		}

		// If a layout container, iterate over children and seed recursion.
		if (view instanceof ViewGroup) {

			for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {

				View innerView = ((ViewGroup) view).getChildAt(i);

				setOnTouchHideKeyboard(activity, innerView);
			}
		}
	}

	public static void pickFile(Activity activity, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		if (requestCode == REQ_EDIT_AVATAR) {
			intent.setType("image/*");
		} else {
			intent.setType("file/*");
			intent.addCategory(Intent.CATEGORY_OPENABLE);
		}
		activity.startActivityForResult(intent, requestCode);
	}

	public static String getRealPathFromURI(Context context, Uri contentURI) {
		if ("file".equalsIgnoreCase(contentURI.getScheme())) {
			return contentURI.getPath();
		}
		String result = "";
		String[] projection = { "_data" };
		Cursor cursor = context.getContentResolver().query(contentURI,
				projection, null, null, null);
		if (cursor == null) { // Source is Dropbox or other similar local file
								// path
			result = contentURI.getPath();
		} else if (cursor.moveToFirst()) {
			int idx = cursor.getColumnIndex("_data");
			result = cursor.getString(idx);
			cursor.close();
		}
		return result;
	}
}
